/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eschool.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.eschool.model.Branch;
import com.eschool.model.Role;
import com.eschool.util.HibernateUtil;
import com.eschool.util.JdbcUtil;

/**
 *
 * @author Ammar
 */
public class RoleDao{
	
	
	public static boolean addRole(Role role) {
    	
    	boolean isInserted = false;
    	
    	Connection connection = JdbcUtil.openConnection();
		
		try{
			CallableStatement storedProc = connection.prepareCall("{ call InsertRole(?,?) }");
			
			storedProc.setString(1, role.getRoleName());
			storedProc.setString(2, role.getDescription());
			
			storedProc.execute();
			
			/*int roleId = 3;
			if(role.getPermissions() != null)
			for (Iterator permIterator = role.getPermissions().iterator(); permIterator.hasNext();) {
				Permission perm = (Permission) permIterator.next();
				
				CallableStatement storedProcPerms = connection.prepareCall("{ call InsertRolePermissions(?,?) }");
				
				storedProcPerms.setInt(1, roleId);
				storedProcPerms.setInt(2, perm.getPermissionId());
				
				storedProcPerms.execute();
			}
			else
				System.out.print("Null");*/
			
			storedProc.execute();
			
			connection.close();
			
			isInserted = true;
		}
		
		catch(Exception e){
			connection.close();
			isInserted = false;
			e.printStackTrace();
		}
		finally{
			return isInserted;
		}
	}

	
	public static Role getRoleByProperty(String property, Object value) {
		
		Session session = HibernateUtil.currentSession();
	      
		Criteria crit = session.createCriteria(Role.class);
		crit.add(Restrictions.eq(property, value));
		
		Role role= (Role) crit.uniqueResult();

        HibernateUtil.closeSession(session);

        return role;
	}
	
	public static List getRoles(Map<String , Object> conditions) {
		
		Session session = HibernateUtil.currentSession();
		Criteria crit = session.createCriteria(Role.class);
		
		if (conditions != null)
			
			for (Iterator iterator = conditions.entrySet().iterator(); iterator.hasNext();) {
			
				Map.Entry condition = (Map.Entry) iterator.next();
				
				crit.add(Restrictions.eq(((String) condition.getKey()), condition.getValue()));
			}
		
		List roles = (List<Role>) crit.list();
		
        HibernateUtil.closeSession(session);
        
        if(roles == null)
        	return Collections.EMPTY_LIST;

        return roles;
	}
	
	public static List<Role> getAllRoles() {
		Session session = HibernateUtil.currentSession();
	      
		Criteria crit = session.createCriteria(Role.class);
		
		List roles = crit.list();
		
        HibernateUtil.closeSession(session);
        return roles;
	}
}
